统计英文句子中的单词词频(用字典)Python编程

您所在的位置:网站首页 python输入一个英文句子 输出单词个数 统计英文句子中的单词词频(用字典)Python编程

统计英文句子中的单词词频(用字典)Python编程

2023-08-11 13:55| 来源: 网络整理| 查看: 265

一、题目:给定一个英文句子,程序最后输出某个单词的词频。

输入格式:

字符串

输出格式:

整数

输入样例(因为oj系统限制,测试用例设为判断英文单词个数(不区分大小写,全部转换成小写字符处理),请注意英文标点,假设仅包含,和.):

not

输出样例:

2

二、题目分析

给定一个英文句子,要用split函数对空格进行分词,可构成一个列表 对列表中单词最后一项进行分析,有标点则去除标点 最后输出要考虑词频为0的情况

三、词频统计

def countfeq(s): s_list=s.split() s_dict={} for item in s_list: if item[-1] in ',.):': item=item[:-1] s_dict[item]=s_dict.get(item,0)+1 ''' if item not in s_dict: s_dict[item]=1 else: s_dict[item]+=1 ''' return s_dict

要新建一个空字典 s_dict[item]=s_dict.get(item,0)+1 这句和下面的注释语句意思一样 即:若单词不在字典key中,value为一;在则加一

四、主函数

if __name__ == "__main__": s = "Not clumsy person in this world, only lazy people, only people can not hold out until the last." s_dict = countfeq(s.lower()) word = input() if word in s_dict: print(s_dict[word]) else: print('0')


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3